package com.rest.converter;

import android.util.Log;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

/**
 * @Description: java类作用描述
 * @Author: lzp
 * @CreateDate: 2022/3/21 10:43
 * @UpdateRemark: 更新说明
 */

public class StringTypeAdapter extends TypeAdapter<String> {

    @Override
    public void write(JsonWriter out, String value) throws IOException {
        try {
            if (value == null) {
                out.nullValue();
                return;
            }
            out.value(value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String read(JsonReader in) throws IOException {
        try {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                Log.e("TypeAdapter", "null is not a string");
                return ""; //原先是返回Null，这里改为返回空字符串
            }
        } catch (Exception e) {
            Log.e("TypeAdapter", "Not a String", e);
        }
        return in.nextString();
    }
}